package com.hotel;

import com.hotel.entity.Book;
import com.hotel.entity.HistoricalSubscription;
import com.hotel.entity.Member;
import com.hotel.entity.Subscription;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

// 房间类型Servlet
@WebServlet(urlPatterns = { "*.book", "/list.hsubscription", "*.subscription" })
public class BookServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        System.out.println(path);
        if ("/list.book".equals(path)) {
            listBooks(req, resp);
        } else if ("/list.hsubscription".equals(path)) {
            listHistoricalSubscriptions(req, resp);
        } else if ("/list.subscription".equals(path)) {
            listSubscriptions(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 可以根据需要实现POST请求的处理
    }

    // 查询房间类型所有信息
    protected void listBooks(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("BookServlet.listBooks");
        req.setCharacterEncoding("UTF-8");
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/hotell?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
            String un = "root";
            String pwd = "root";
            con = DriverManager.getConnection(url, un, pwd);
            ps = con.prepareStatement("SELECT * FROM book");
            rs = ps.executeQuery();
            List<Book> books = new ArrayList<>();
            while (rs.next()) {
                Book book = new Book();
                book.setId(rs.getInt("id"));
                book.setName(rs.getString("name"));
                book.setAuthor(rs.getString("author"));
                book.setIntroduce(rs.getString("introduce"));
                books.add(book);
            }
            req.setAttribute("cgs", books);
            req.getRequestDispatcher("hotel/bookList.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeResources(rs, ps, con);
        }
    }

    // 查询历史订阅
    protected void listHistoricalSubscriptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession();
        Member member = (Member) session.getAttribute("member");

        if (member != null) {
            Connection con = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                // 使用北京时间的时区设置
                Class.forName("com.mysql.cj.jdbc.Driver");
                String url = "jdbc:mysql://127.0.0.1:3306/hotell?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
                String un = "root";
                String pwd = "root";
                con = DriverManager.getConnection(url, un, pwd);
                ps = con.prepareStatement("SELECT * FROM subscription");
                rs = ps.executeQuery();

                List<HistoricalSubscription> historicalSubscriptions = new ArrayList<>();
                while (rs.next()) {
                    HistoricalSubscription subscription = new HistoricalSubscription();
                    subscription.setNo(rs.getString("no"));
                    subscription.setLinkman(rs.getString("linkman"));
                    subscription.setEmail(rs.getString("email"));
                    subscription.setPhone(rs.getString("phone"));

                    // 获取时间戳并转换为北京时间
                    Timestamp cretime = rs.getTimestamp("cretime");
                    subscription.setCretime(cretime);

                    // 格式化为北京时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                    String beijingTime = sdf.format(cretime);
                    System.out.println("Cretime (Beijing Time): " + beijingTime);

                    // 获取状态描述
                    int statusAuthor = rs.getInt("status");
                    String statusIntroduce = getStatusIntroduce(statusAuthor);
                    subscription.setStatus(statusIntroduce);

                    historicalSubscriptions.add(subscription);
                }

                req.setAttribute("historicalOrders", historicalSubscriptions);
                req.getRequestDispatcher("hotel/historySubscription.jsp").forward(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeResources(rs, ps, con);
            }
        } else {
            sendRedirectToLogin(req, resp);
        }
    }


    // 查询当前用户的订阅
    protected void listSubscriptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession();
        Member member = (Member) session.getAttribute("member");

        if (member != null) {
            System.out.println("BookServlet.listSubscriptions");

            Connection con = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                String url = "jdbc:mysql://127.0.0.1:3306/hotell?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
                String un = "root";
                String pwd = "root";
                con = DriverManager.getConnection(url, un, pwd);
                ps = con.prepareStatement("SELECT * FROM subscription WHERE status = '1' OR status = '2'");
                rs = ps.executeQuery();

                List<Subscription> subscriptions = new ArrayList<>();
                while (rs.next()) {
                    Subscription subscription = new Subscription();
                    subscription.setNo(rs.getString("no"));
                    subscription.setLinkman(rs.getString("linkman"));
                    subscription.setEmail(rs.getString("email"));
                    subscription.setPhone(rs.getString("phone"));
                    Timestamp cretime = rs.getTimestamp("cretime");

                    // Convert to Beijing time
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                    String beijingTime = sdf.format(cretime);
                    subscription.setCretime(cretime); // 也可以考虑使用Timestamp
                    System.out.println("Cretime (Beijing Time): " + beijingTime);

                    subscriptions.add(subscription);
                }

                req.setAttribute("cgs", subscriptions);
                req.getRequestDispatcher("hotel/memberCenter.jsp").forward(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeResources(rs, ps, con);
            }
        } else {
            sendRedirectToLogin(req, resp);
        }
    }

    // 获取状态描述
    private String getStatusIntroduce(int statusAuthor) {
        switch (statusAuthor) {
            case 0: return "取消";
            case 1: return "确定";
            case 2: return "未生效";
            default: return "未知状态";
        }
    }

    // 关闭资源的通用方法
    private void closeResources(ResultSet rs, PreparedStatement ps, Connection con) {
        if (rs != null) try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
        if (ps != null) try { ps.close(); } catch (SQLException e) { e.printStackTrace(); }
        if (con != null) try { con.close(); } catch (SQLException e) { e.printStackTrace(); }
    }

    // 重定向到登录页面
    private void sendRedirectToLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("<script type='text/javascript'>");
        out.println("alert('请先登录！');");
        out.println("window.location.href='" + req.getContextPath() + "/hotel/index.jsp';");
        out.println("</script>");
        out.close();
    }
}
